var testMatrix = [ [ 1, 2, 0, 4 ], [ 0, 3, 2, 1 ], [ 2, 1, 4, 0 ],
		[ 3, 0, 1, 2 ] ];

function isSolvable(matrix) {
	for ( var i = 0; i < matrix.length; i++) {
		for ( var j = 0; j < matrix[0].length; j++) {
			var number = matrix[i][j];
			if (number > 0) {
				for ( var k = j + 1; k < matrix[i].length; k++) {
					if (number == matrix[i][k]) {
						return false;
					}
				}
			}
		}
	}
	for ( var i = 0; i < matrix[0].length; i++) {
		for ( var j = 0; j < matrix.length; j++) {
			var number = matrix[j][i];
			if (number > 0) {
				for ( var k = j + 1; k < matrix.length; k++) {
					if (number == matrix[k][i]) {
						return false;
					}
				}
			}
		}
	}

	var newMatrix = [ [ 0, 0, 0, 0 ], [ 0, 0, 0, 0 ], [ 0, 0, 0, 0 ],
			[ 0, 0, 0, 0 ] ];
	for ( var i = 0; i < matrix.length; i++) {
		var column = 0;
		column += (i % 2) * 2;
		for ( var j = 0; j < matrix[i].length; j++) {
			var row = Math.floor(j / 2) + Math.floor(i / 2) * 2;
			if (j > 0 && j % 2 == 0) {
				column -= 2;
			}
			newMatrix[row][column] = matrix[i][j];
			column++;
		}
	}

	for ( var i = 0; i < newMatrix.length; i++) {
		for ( var j = 0; j < newMatrix[0].length; j++) {
			var number = newMatrix[i][j];
			if (number > 0) {
				for ( var k = j + 1; k < newMatrix[i].length; k++) {
					if (number == newMatrix[i][k]) {
						return false;
					}
				}
			}
		}
	}
	return true;
}

function findSolution(matrix) {
	if(isSolvable(matrix)){
		solve(0,0,matrix);
		drawNumbers(matrix);
		return true;
	} else {
		return false;
	}
}

function solve(i,j,matrix){
	if(i == 4){
		i = 0;
		if(++j == 4)
			return true;
	}
	if(matrix[i][j] != 0){
		return solve(i+1,j,matrix);
	}
	for ( var val = 1; val <= 4; val++) {
		if(legal(i, j, val, matrix)){
			matrix[i][j] = val;
			if(solve(i+1, j, matrix)){
				return true;
			}
		}
	}
	matrix[i][j] = 0;
	return false;
}


function legal(i, j, val, matrix){
	for ( var k = 0; k < 4; k++) {
		if (val == matrix[k][j]){
			return false;
		}
	}
	for ( var k = 0; k < 4; k++) {
		if (val == matrix[i][k]){
			return false;
		}
	}
	

	var boxRowOffset = Math.floor(i / 2) * 2;
	var boxColOffset = Math.floor(j / 2) * 2;
	for (var k = 0; k < 2; ++k)
		for (var m = 0; m < 2; ++m)
			if (val == matrix[boxRowOffset + k][boxColOffset + m])
				return false;

	return true;
}